import matplotlib.pyplot as plt
from worker import Worker
from settings import FILES_DIR
import os
import json


class Group:
    def __init__(self, config: dict, level=1):
        self.config = config
        output_name = config.get('输出')
        

        try:
            if config.get('左线'):
                is_valid, info = self.is_valid_config(config.get('左线'))
                if not is_valid:
                    print(info)
                else:
                    other = config['左线'].get('其他')
                    if isinstance(other, str):
                        other = other if os.path.isabs(
                            other) else os.path.join(FILES_DIR, other)
                        other = json.load(open(other))

                    self.worker_l = Worker(config['左线']['直曲'], config['左线']['竖曲'], other_stacks=other,
                                        reverse=True, output_name=output_name, config=config, level=level)
            if config.get('右线'):
                is_valid, info = self.is_valid_config(config.get('右线'))
                if not is_valid:
                    print(info)
                else:
                    other = config['右线'].get('其他')
                    if isinstance(other, str):
                        other = other if os.path.isabs(
                            other) else os.path.join(FILES_DIR, other)
                        other = json.load(open(other))

                    self.worker_r = Worker(config['右线']['直曲'], config['右线']['竖曲'], other_stacks=other,
                                        reverse=False, output_name=output_name, config=config, level=level)

        except KeyError as err:
            print(f'缺少键:{err}')
            raise err
        except FileNotFoundError:
            print("文件没有找到")

    def run(self):
        if getattr(self, 'worker_l', None) is not None:
            self.worker_l.run()
        if getattr(self, 'worker_r', None) is not None:
            self.worker_r.run()

    @staticmethod
    def is_valid_config(config):
        if config is None:
            return True
        s = config.get("直曲")
        v = config.get("竖曲")
        if not isinstance(s, list):
            return False, '直曲表配置不正确'
        if not isinstance(v, list):
            return False, '竖曲表配置不正确'
        if not len(s) == len(v):
            return False, '直曲表竖曲表文件个数不匹配'
        other = config.get('其他')
        if other is not None and not other:
            return False, '“其他”文件名不正确'
        output = config.get('输出')
        if output is not None and not other:
            return False, '"输出"配置不正确'
        
        return True, ''